using System.Web.Mvc;
using Limestone;
using Limestone.MVC;

namespace SampleSite.Areas.Limestone.Controllers
{
    public class TemplateDesignerController : Controller
    {
        private readonly ITemplateProvider _templateProvider;
        private readonly FieldFactory _fieldFactory;

        public TemplateDesignerController(ITemplateProvider templateProvider, FieldFactory fieldFactory)
        {
            _templateProvider = templateProvider;
            _fieldFactory = fieldFactory;
        }

        public ActionResult Index()
        {
            return View(_templateProvider.GetAll());
        }

        public ActionResult New(DesignedTemplate template)
        {
            if (template != null && template.Name != null)
                return Save(template);
            template = new DesignedTemplate();
            return View("TemplateDesigner", template);
        }

        [HttpGet]
        public ActionResult Edit(string templatePath)
        {
            var template = _templateProvider.Get(templatePath);
            if (template == null)
                return View("Error");

            return View("TemplateDesigner", template.ToDesignedTemplate());
        }

        [HttpPost]
        public ActionResult Save(DesignedTemplate designedTemplate)
        {
            var newTemplate = _templateProvider.Save(designedTemplate.ToIPageTemplate());
            
            return View("TemplateDesigner", newTemplate.ToDesignedTemplate());
        }

        public ActionResult Design(DesignedTemplate template)
        {
            if (!string.IsNullOrEmpty(template.NewFieldName))
            {
                var fldSet = _fieldFactory.CreateFieldSetting(template.NewFieldType);
                template.FieldSettings.Add(fldSet);
            }
            template.NewFieldName = string.Empty;
            return View("TemplateDesigner", template);
        }
    }
}